package com.ideal.hadoopadmin.common.util.plugins.handler;

import com.ideal.hadoopadmin.common.util.DBUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Date;

/**
 * Created by CC on 2016/2/29.
 */
public class TimeTypeHandler implements TypeHandler<Date>{


    @Override
    public void setParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType) throws SQLException {
        Date date=(Date)parameter;
        if(date==null){
//            ps.setLong(i,System.currentTimeMillis());
            date=new Date();
        }else{
            Long time= null;
            try {
                time = DBUtils.parseDate(null, date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            ps.setLong(i,time);
        }
    }

    @Override
    public Date getResult(ResultSet rs, String columnName) throws SQLException {
        Long time=rs.getLong(columnName);
        return DBUtils.formatDate(null,time);
    }

    @Override
    public Date getResult(ResultSet rs, int columnIndex) throws SQLException {
        Long time=rs.getLong(columnIndex);
        return DBUtils.formatDate(null,time);
    }

    @Override
    public Date getResult(CallableStatement cs, int columnIndex) throws SQLException {
        Long time=cs.getLong(columnIndex);
        return DBUtils.formatDate(null,time);
    }
}
